package com.team.engine.user.action;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.team.engine.common.cache.SessionCache;
import com.team.engine.common.exception.BaseServiceException;
import com.team.engine.user.dao.UserGroup;
import com.team.engine.user.dao.UserNav;
import com.team.engine.user.service.UserServiceImpl;
import com.team.engine.util.SubPage;
import com.team.engine.util.WebUtilsNative;

@Controller
@RequestMapping(value="/user")
public class UserController {

	@Resource
	private UserServiceImpl userServiceImpl;
	
	public void setUserServiceImpl(UserServiceImpl userServiceImpl) {
		this.userServiceImpl = userServiceImpl;
	}
	
	private String toPath(String pageName){
		return "user" + "/" + pageName;
	}
	
	/**
	 * 返回用户列表
	 * @param model
	 * @param request
	 * @return
	 * @throws RuntimeException
	 */
	@RequestMapping(value="/get", method=RequestMethod.GET)
	public String getUserList(Model model, HttpServletRequest request, HttpSession session) throws RuntimeException {
		String page = request.getParameter("page");
//		SubPage<UserNav> sub = this.userServiceImpl.getUserAll(page);
		Map<HttpSession, Object> jsession = SessionCache.getInstance().getJsession();
		String sessionValue = String.valueOf((Long) jsession.get(session));
		SubPage<UserNav> sub = this.userServiceImpl.getUserAllWithGroup(page, sessionValue);
		
		model.addAttribute(sub);
		
		return toPath("user_list");
	}
	
	/**
	 * 添加一个用户
	 * @param session
	 * @param userNav
	 * @param result
	 * @param model
	 * @param request
	 * @return
	 * @throws RuntimeException
	 * @throws BaseServiceException
	 */
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String addUser(HttpSession session, UserNav userNav, BindingResult result, Model model, HttpServletRequest request) throws RuntimeException, BaseServiceException {
		
		boolean hasErrors = result.hasErrors();
		
		// user/user_list.jsp
		String errorPath = "user/user_list";
		String successPath = "redirect:get";
		
		//检查是否重复提交
		boolean checkToken = WebUtilsNative.isCheckToken(request.getParameter("token"), session);
		if(checkToken){
			model.addAttribute("error", "请勿重复提交");
			return errorPath;
		}
		
		//表单输入验证
		String resultMsg = this.checkUserInput(userNav);
		if(resultMsg.length() > 0){
			model.addAttribute("error", resultMsg);
			return errorPath;
		}
		
		//验证用户名是否重复
		if(this.userServiceImpl.isUserRepeat(userNav)){
			model.addAttribute("error", "用户名重复");
			return errorPath;
		}
		
		//用户数据保存操作
		boolean f = userServiceImpl.addUser(userNav);
		if (!f){
			model.addAttribute("error", "数据保存失败");
			return errorPath;
		}
		
		return successPath;
	}

	/**
	 * user（用户）表单输入验证
	 * @param userNav
	 * @return
	 */
	private String checkUserInput(UserNav userNav){
		String resultMsg = "";
		String name = userNav.getName();
		if(userNav == null || name.trim().length()==0)
			return resultMsg = "请输入姓名";
		
		if(String.valueOf(name.charAt(0)).matches("^[\\w]") || name.contains("\u0020"))
			return resultMsg = "只能以字母和数字开头，且不允许空格";
		
		if(name.length()>20)
			return resultMsg = "用户名最长只能是20个字符";
		
		return resultMsg;
	}
	
	@RequestMapping(value="/group/get", method=RequestMethod.GET)
	public String getUserGroup(Model model, HttpServletRequest request){
		String page = request.getParameter("page");
		SubPage<UserGroup> userGroupAll = this.userServiceImpl.getUsergroupAll(page);
		model.addAttribute("result", userGroupAll.getResultList());
		model.addAttribute("totalPage", userGroupAll.getTotalPage());
		model.addAttribute("thisPage", userGroupAll.getThisPage());
		
		return null;
	}
	
	@RequestMapping(value="/group/add", method=RequestMethod.POST)
	public String addUserGroup(HttpSession session, UserGroup userGroup, BindingResult result, Model model, HttpServletRequest request) throws RuntimeException, BaseServiceException {
		
		boolean hasErrors = result.hasErrors();
		
		// user/user_list.jsp
		String errorPath = "/user/usergroup_list";
		String successPath = "redirect:/group/get";
		
		//检查是否重复提交
		boolean checkToken = WebUtilsNative.isCheckToken(request.getParameter("token"), session);
		if(checkToken){
			model.addAttribute("error", "请勿重复提交");
			return errorPath;
		}
		
		//表单输入验证
		String resultMsg = this.checkUserGroupInput(userGroup);
		if(resultMsg.length() > 0){
			model.addAttribute("error", resultMsg);
			return errorPath;
		}
		
		//验证用户名是否重复
		if(this.userServiceImpl.isUsergroupRepeat(userGroup)){
			model.addAttribute("error", "用户名组重复");
			return errorPath;
		}
		
		//用户数据保存操作
		boolean f = userServiceImpl.addUserGroup(userGroup);
		if (!f){
			model.addAttribute("error", "数据保存失败");
			return errorPath;
		}
		
		return successPath;
	}
	
	/**
	 * usergroup（用户组）表单输入验证
	 * @param userGroup
	 * @return
	 */
	private String checkUserGroupInput(UserGroup userGroup){
		String resultMsg = "";
		String name = userGroup.getNameNav();
		if(userGroup == null || name.trim().length()==0)
			return resultMsg = "请输入用户组名";
		
		if(name.contains("\u0020"))
			return resultMsg = "不允许空格";
		
		if(name.length()>20)
			return resultMsg = "用户组名最长只能是20个字符";
		
		return resultMsg;
	}
	
	
	/**
	 * 关联用户组和用户
	 * 
	 * @return
	 */
	@RequestMapping(value="/link{flag}/add", method=RequestMethod.GET)
	public String linkUserGroupUser(HttpSession session,
			@PathVariable String flag,
			@RequestParam String userId,
			@RequestParam String groupId,
			@RequestParam String  page
			){
		String errorPath = "user/usergroup_list";
		String successPath = "redirect:/group/get";
		String id = session.getId();
		
		return errorPath;
	}
	
}
